package com.systop.asset.controller;

import com.systop.asset.entity.ProcessTemplate;
import com.systop.asset.entity.RestResponse;
import com.systop.asset.enums.HttpCodeEnum;
import com.systop.asset.service.IProcessTemplateService;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;


/**
 * 审批模板Controller
 * 
 * @author mu
 * @date 2025-06-24
 */
@RestController
@RequestMapping("/process/template")
public class ProcessTemplateController {
    @Autowired
    private IProcessTemplateService processTemplateService;

    /**
     * 查询审批模板列表
     */
    //@PreAuthorize("@ss.hasPermi('asset:template:list')")
    @GetMapping("/list")
    public RestResponse list(ProcessTemplate processTemplate)
    {
        List<ProcessTemplate> list = processTemplateService.selectProcessTemplateList(processTemplate);
        return RestResponse.success(list);
    }



    /**
     * 获取审批模板详细信息
     */
    //@PreAuthorize("@ss.hasPermi('asset:template:query')")
    @GetMapping(value = "/{id}")
    public RestResponse getInfo(@PathVariable("id") Long id)
    {
        return RestResponse.success(processTemplateService.selectProcessTemplateById(id));
    }

    //文件上传的根路径
    @Value("${upload.path}")
    private String rootPath;
    /**
     * 新增审批模板并进行部署
     * @param processTemplate 上传的模板
     * @param file zip文件
     * @return
     */
    //@PreAuthorize("@ss.hasPermi('asset:template:add')")
    @PostMapping
    public RestResponse add(ProcessTemplate processTemplate, MultipartFile file)
    {
        //实现文件上传
        if (file== null || file.isEmpty()){
            return RestResponse.failure(504,"上传文件不能为空");
        }
        String oldName = file.getOriginalFilename();
        if(oldName.lastIndexOf(".zip")==-1){
            return RestResponse.failure(HttpCodeEnum.INVALID_FILE_TYPE);
        }
        //文件存储路径
        File path = new File(rootPath+"/bpmnFile/");
        if (!path.exists()){
            path.mkdirs();
        }
        //文件名称
        String processDefinitionPath = System.currentTimeMillis() +"-"+ file.getOriginalFilename();
        File uploadFile = new File(path,processDefinitionPath);
        //输出文件
        try {
            file.transferTo(uploadFile);
            //设置文件路径
            processTemplate.setProcessDefinitionPath("/bpmnFile/"+processDefinitionPath);
            //调用业务层，实现流程模板的新增和部署
            return processTemplateService.insertProcessTemplate(processTemplate);
        } catch (IOException e) {
            e.printStackTrace();
            return RestResponse.failure(HttpCodeEnum.FILE_UPLOAD_FAILURE); //文件上传失败
        }
    }

    /**
     * 修改审批模板
     */
    //@PreAuthorize("@ss.hasPermi('asset:template:edit')")
    @PutMapping
    public RestResponse edit(@RequestBody ProcessTemplate processTemplate)
    {
        return RestResponse.success(processTemplateService.updateProcessTemplate(processTemplate));
    }

    /**
     * 删除审批模板
     */
    //@PreAuthorize("@ss.hasPermi('asset:template:remove')")
	@DeleteMapping("/{id}")
    public RestResponse remove(@PathVariable Long id)
    {
        return processTemplateService.deleteProcessTemplateByIds(id);
    }

    /**
     * 搜索部署文件
     * @param id 模板id
     * @param type 文件类型：xml或者png
     * @return
     */
    //@PreAuthorize("@ss.hasPermi('asset:template:remove')")
    @GetMapping("/getBpmnFile/{id}/{type}")
    public void getBpmnFile(@PathVariable("id") Long id,
                            @PathVariable("type")  String type,
                            HttpServletResponse response ) throws IOException {
        InputStream bpmnFile = processTemplateService.getBpmnFile(id,type);
        try {
            IOUtils.copy(bpmnFile,response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            bpmnFile.close();
        }
    }
}
